const express = require('express');
const cors = require('cors');
require('dotenv').config();

const { query, paginatedQuery, testConnection } = require('./config/database');

const app = express();
const PORT = process.env.API_PORT || 3001;

// 中间件
app.use(cors()); // 允许跨域请求
app.use(express.json()); // 解析JSON请求体
app.use(express.static('public')); // 静态文件服务
app.use('/images', express.static('src/assets/images')); // 图片静态文件服务

// 请求日志中间件
app.use((req, res, next) => {
  console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`);
  next();
});

// ==================== API 路由 ====================

// 1. 领养案例 API
app.get('/api/adoption-cases', async (req, res) => {
  try {
    const { search, page = 1, pageSize = 6 } = req.query;
    
    let sql = `
      SELECT id, name, image, status, adopter, age, gender, breed, 
             health, \`character\`, description, rescue_date, adoption_date, photos,
             created_at, updated_at
      FROM adoption_cases 
      WHERE 1=1
    `;
    const params = [];
    
    if (search) {
      sql += ` AND (name LIKE ? OR adopter LIKE ? OR description LIKE ? OR breed LIKE ?)`;
      const searchTerm = `%${search}%`;
      params.push(searchTerm, searchTerm, searchTerm, searchTerm);
    }
    
    sql += ` ORDER BY created_at DESC`;
    
    const result = await paginatedQuery(sql, params, page, pageSize);
    
    // 处理photos字段（JSON字符串转换为数组）
    result.data = result.data.map(item => {
      let photos = [];
      if (item.photos) {
        try {
          // 如果photos已经是数组，直接使用
          if (Array.isArray(item.photos)) {
            photos = item.photos;
          } else {
            // 尝试解析JSON字符串
            photos = JSON.parse(item.photos);
          }
        } catch (error) {
          console.error(`解析photos字段失败 (id: ${item.id}):`, error.message);
          console.error(`原始数据:`, item.photos);
          // 如果解析失败，尝试其他格式或使用空数组
          photos = [];
        }
      }
      return {
        ...item,
        photos: photos
      };
    });
    
    res.json({
      success: true,
      ...result
    });
  } catch (error) {
    console.error('获取领养案例失败:', error);
    res.status(500).json({ success: false, message: '获取领养案例失败', error: error.message });
  }
});

app.get('/api/adoption-cases/:id', async (req, res) => {
  try {
    const results = await query(
      'SELECT * FROM adoption_cases WHERE id = ?',
      [req.params.id]
    );
    
    if (results.length === 0) {
      return res.status(404).json({ success: false, message: '案例不存在' });
    }
    
    const caseItem = results[0];
    // 处理photos字段
    if (caseItem.photos) {
      caseItem.photos = JSON.parse(caseItem.photos);
    }
    
    res.json({ success: true, data: caseItem });
  } catch (error) {
    console.error('获取案例详情失败:', error);
    res.status(500).json({ success: false, message: '获取案例详情失败', error: error.message });
  }
});

// 2. 宠物知识 API
app.get('/api/pet-knowledge', async (req, res) => {
  try {
    const { search, page = 1, pageSize = 10 } = req.query;
    
    let sql = `
      SELECT id, title, date, category, author, summary, content, 
             tags, read_count, like_count, created_at, updated_at
      FROM knowledge_articles 
      WHERE category = 'knowledge' AND status = 'published'
    `;
    const params = [];
    
    if (search) {
      sql += ` AND (title LIKE ? OR content LIKE ? OR summary LIKE ?)`;
      const searchTerm = `%${search}%`;
      params.push(searchTerm, searchTerm, searchTerm);
    }
    
    sql += ` ORDER BY date DESC, created_at DESC`;
    
    const result = await paginatedQuery(sql, params, page, pageSize);
    
    // 处理tags字段
    result.data = result.data.map(item => ({
      ...item,
      tags: item.tags ? JSON.parse(item.tags) : []
    }));
    
    res.json({
      success: true,
      ...result
    });
  } catch (error) {
    console.error('获取宠物知识失败:', error);
    res.status(500).json({ success: false, message: '获取宠物知识失败', error: error.message });
  }
});

// 3. 宠物新闻 API
app.get('/api/pet-news', async (req, res) => {
  try {
    const { search, page = 1, pageSize = 10 } = req.query;
    
    let sql = `
      SELECT id, title, date, category, author, summary, content, 
             tags, read_count, like_count, created_at, updated_at
      FROM knowledge_articles 
      WHERE category = 'news' AND status = 'published'
    `;
    const params = [];
    
    if (search) {
      sql += ` AND (title LIKE ? OR content LIKE ? OR summary LIKE ?)`;
      const searchTerm = `%${search}%`;
      params.push(searchTerm, searchTerm, searchTerm);
    }
    
    sql += ` ORDER BY date DESC, created_at DESC`;
    
    const result = await paginatedQuery(sql, params, page, pageSize);
    
    // 处理tags字段
    result.data = result.data.map(item => ({
      ...item,
      tags: item.tags ? JSON.parse(item.tags) : []
    }));
    
    res.json({
      success: true,
      ...result
    });
  } catch (error) {
    console.error('获取宠物新闻失败:', error);
    res.status(500).json({ success: false, message: '获取宠物新闻失败', error: error.message });
  }
});

// 4. 文章详情 API (知识+新闻)
app.get('/api/articles/:id', async (req, res) => {
  try {
    const results = await query(
      'SELECT * FROM knowledge_articles WHERE id = ? AND status = "published"',
      [req.params.id]
    );
    
    if (results.length === 0) {
      return res.status(404).json({ success: false, message: '文章不存在' });
    }
    
    const article = results[0];
    // 处理tags字段
    if (article.tags) {
      article.tags = JSON.parse(article.tags);
    }
    
    // 增加阅读量
    await query(
      'UPDATE knowledge_articles SET read_count = read_count + 1 WHERE id = ?',
      [req.params.id]
    );
    article.read_count += 1;
    
    res.json({ success: true, data: article });
  } catch (error) {
    console.error('获取文章详情失败:', error);
    res.status(500).json({ success: false, message: '获取文章详情失败', error: error.message });
  }
});

// 5. 救助案例 API
app.get('/api/rescue-cases/:type', async (req, res) => {
  try {
    const { type } = req.params; // cats, dogs, others
    
    let dbType;
    switch(type) {
      case 'cats': dbType = 'cat'; break;
      case 'dogs': dbType = 'dog'; break;
      case 'others': dbType = 'other'; break;
      default: 
        return res.status(400).json({ success: false, message: '无效的类型参数' });
    }
    
    const results = await query(
      'SELECT * FROM rescue_cases WHERE type = ? ORDER BY rescue_date DESC',
      [dbType]
    );
    
    res.json({ success: true, data: results });
  } catch (error) {
    console.error('获取救助案例失败:', error);
    res.status(500).json({ success: false, message: '获取救助案例失败', error: error.message });
  }
});

// 6. 留言板 API
app.get('/api/guestbook', async (req, res) => {
  try {
    const { page = 1, pageSize = 10 } = req.query;
    
    const sql = `
      SELECT id, title, name, tel, email, address, content, 
             reply_content, reply_time, created_at
      FROM guestbook 
      WHERE status = 'approved'
      ORDER BY created_at DESC
    `;
    
    const result = await paginatedQuery(sql, [], page, pageSize);
    
    res.json({
      success: true,
      ...result
    });
  } catch (error) {
    console.error('获取留言失败:', error);
    res.status(500).json({ success: false, message: '获取留言失败', error: error.message });
  }
});

app.post('/api/guestbook', async (req, res) => {
  try {
    const { title, name, tel, email, address, content } = req.body;
    
    // 基础验证
    if (!name || !tel || !content) {
      return res.status(400).json({ success: false, message: '姓名、手机和留言内容不能为空' });
    }
    
    // 手机号格式验证
    const telRegex = /^(((13[0-9]{1})|(14[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(17[0-9]{1})|(18[0-9]{1})|(19[0-9]{1}))+\d{8})$/;
    if (!telRegex.test(tel)) {
      return res.status(400).json({ success: false, message: '手机号码格式不正确' });
    }
    
    // 获取客户端IP
    const ipAddress = req.headers['x-forwarded-for'] || 
                     req.connection.remoteAddress || 
                     req.socket.remoteAddress ||
                     req.ip || 
                     'unknown';
    
    const result = await query(`
      INSERT INTO guestbook (title, name, tel, email, address, content, ip_address, status)
      VALUES (?, ?, ?, ?, ?, ?, ?, 'pending')
    `, [
      title || '无标题',
      name,
      tel,
      email || '',
      address || '',
      content,
      ipAddress
    ]);
    
    res.json({ 
      success: true, 
      message: '留言提交成功，等待审核', 
      data: { 
        id: result.insertId,
        status: 'pending'
      } 
    });
  } catch (error) {
    console.error('提交留言失败:', error);
    res.status(500).json({ success: false, message: '提交留言失败', error: error.message });
  }
});

// 7. 联系信息 API
app.get('/api/contact-info', async (req, res) => {
  try {
    const results = await query('SELECT * FROM contact_info LIMIT 1');
    
    if (results.length === 0) {
      return res.status(404).json({ success: false, message: '联系信息不存在' });
    }
    
    res.json({ success: true, data: results[0] });
  } catch (error) {
    console.error('获取联系信息失败:', error);
    res.status(500).json({ success: false, message: '获取联系信息失败', error: error.message });
  }
});

// 8. 网站配置 API
app.get('/api/site-config', async (req, res) => {
  try {
    const results = await query('SELECT * FROM site_config LIMIT 1');
    
    if (results.length === 0) {
      return res.status(404).json({ success: false, message: '网站配置不存在' });
    }
    
    const config = results[0];
    // 处理social_media字段
    if (config.social_media) {
      config.social_media = JSON.parse(config.social_media);
    }
    
    res.json({ success: true, data: config });
  } catch (error) {
    console.error('获取网站配置失败:', error);
    res.status(500).json({ success: false, message: '获取网站配置失败', error: error.message });
  }
});

// 9. 管理接口 - 留言审核（可选）
app.patch('/api/admin/guestbook/:id', async (req, res) => {
  try {
    const { status, reply_content } = req.body;
    const { id } = req.params;
    
    if (!['approved', 'rejected'].includes(status)) {
      return res.status(400).json({ success: false, message: '无效的状态' });
    }
    
    let sql = 'UPDATE guestbook SET status = ?';
    let params = [status];
    
    if (status === 'approved' && reply_content) {
      sql += ', reply_content = ?, reply_time = NOW()';
      params.push(reply_content);
    }
    
    sql += ' WHERE id = ?';
    params.push(id);
    
    const result = await query(sql, params);
    
    if (result.affectedRows === 0) {
      return res.status(404).json({ success: false, message: '留言不存在' });
    }
    
    res.json({ success: true, message: '留言状态更新成功' });
  } catch (error) {
    console.error('更新留言状态失败:', error);
    res.status(500).json({ success: false, message: '更新留言状态失败', error: error.message });
  }
});

// 健康检查接口
app.get('/api/health', async (req, res) => {
  try {
    // 测试数据库连接
    await query('SELECT 1');
    
    res.json({ 
      success: true, 
      message: '流浪动物之家 API 服务正常运行（数据库版）', 
      timestamp: new Date().toISOString(),
      version: '2.0.0-database',
      database: 'MySQL'
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      message: '数据库连接失败', 
      error: error.message 
    });
  }
});

// 7. 页面内容 API
app.get('/api/page-content/:pageKey', async (req, res) => {
  try {
    const { pageKey } = req.params;
    
    const sql = `
      SELECT page_key, title, content, meta_description, updated_at
      FROM page_contents 
      WHERE page_key = ? AND status = 'active'
    `;
    
    const results = await query(sql, [pageKey]);
    
    if (results.length === 0) {
      return res.status(404).json({
        success: false,
        message: '页面内容未找到'
      });
    }
    
    res.json({
      success: true,
      data: results[0]
    });
  } catch (error) {
    console.error('获取页面内容失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '获取页面内容失败', 
      error: error.message 
    });
  }
});

// 8. 联系信息 API
app.get('/api/contact-info', async (req, res) => {
  try {
    const sql = `
      SELECT name, phone, tel, fax, email, address, postcode, 
             working_hours, emergency_contact, updated_at
      FROM contact_info 
      ORDER BY id DESC LIMIT 1
    `;
    
    const results = await query(sql);
    
    res.json({
      success: true,
      data: results[0] || {}
    });
  } catch (error) {
    console.error('获取联系信息失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '获取联系信息失败', 
      error: error.message 
    });
  }
});

// 9. 知识文章 API
app.get('/api/knowledge-articles', async (req, res) => {
  try {
    const { search, page = 1, pageSize = 10 } = req.query;
    
    let sql = `
      SELECT id, title, date, author, summary, read_count, status, created_at
      FROM knowledge_articles 
      WHERE category = 'knowledge' AND status = 'published'
    `;
    const params = [];
    
    if (search) {
      sql += ` AND (title LIKE ? OR summary LIKE ? OR content LIKE ?)`;
      const searchTerm = `%${search}%`;
      params.push(searchTerm, searchTerm, searchTerm);
    }
    
    sql += ` ORDER BY date DESC`;
    
    const result = await paginatedQuery(sql, params, page, pageSize);
    
    res.json({
      success: true,
      ...result
    });
  } catch (error) {
    console.error('获取知识文章失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '获取知识文章失败', 
      error: error.message 
    });
  }
});

// 10. 新闻文章 API
app.get('/api/news-articles', async (req, res) => {
  try {
    const { search, page = 1, pageSize = 10 } = req.query;
    
    let sql = `
      SELECT id, title, date, author, summary, read_count, status, created_at
      FROM knowledge_articles 
      WHERE category = 'news' AND status = 'published'
    `;
    const params = [];
    
    if (search) {
      sql += ` AND (title LIKE ? OR summary LIKE ? OR content LIKE ?)`;
      const searchTerm = `%${search}%`;
      params.push(searchTerm, searchTerm, searchTerm);
    }
    
    sql += ` ORDER BY date DESC`;
    
    const result = await paginatedQuery(sql, params, page, pageSize);
    
    res.json({
      success: true,
      ...result
    });
  } catch (error) {
    console.error('获取新闻文章失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '获取新闻文章失败', 
      error: error.message 
    });
  }
});

// 11. 文章详情 API
app.get('/api/articles/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    const sql = `
      SELECT id, title, date, category, author, summary, content, 
             tags, read_count, like_count, status, created_at, updated_at
      FROM knowledge_articles 
      WHERE id = ? AND status = 'published'
    `;
    
    const results = await query(sql, [id]);
    
    if (results.length === 0) {
      return res.status(404).json({
        success: false,
        message: '文章未找到'
      });
    }
    
    // 更新阅读次数
    const updateSql = `UPDATE knowledge_articles SET read_count = read_count + 1 WHERE id = ?`;
    await query(updateSql, [id]);
    
    const article = results[0];
    article.read_count += 1; // 更新返回数据中的阅读次数
    
    res.json({
      success: true,
      data: article
    });
  } catch (error) {
    console.error('获取文章详情失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '获取文章详情失败', 
      error: error.message 
    });
  }
});

// 获取系统统计信息
app.get('/api/stats', async (req, res) => {
  try {
    const [adoptionCount] = await query('SELECT COUNT(*) as count FROM adoption_cases');
    const [knowledgeCount] = await query('SELECT COUNT(*) as count FROM knowledge_articles WHERE category = "knowledge"');
    const [newsCount] = await query('SELECT COUNT(*) as count FROM knowledge_articles WHERE category = "news"');
    const [rescueCount] = await query('SELECT COUNT(*) as count FROM rescue_cases');
    const [guestbookCount] = await query('SELECT COUNT(*) as count FROM guestbook WHERE status = "approved"');
    
    res.json({
      success: true,
      data: {
        adoption_cases: adoptionCount.count,
        knowledge_articles: knowledgeCount.count,
        news_articles: newsCount.count,
        rescue_cases: rescueCount.count,
        approved_messages: guestbookCount.count
      }
    });
  } catch (error) {
    console.error('获取统计信息失败:', error);
    res.status(500).json({ success: false, message: '获取统计信息失败', error: error.message });
  }
});

// 错误处理中间件
app.use((error, req, res, next) => {
  console.error('服务器错误:', error);
  res.status(500).json({
    success: false,
    message: '服务器内部错误',
    error: process.env.NODE_ENV === 'development' ? error.message : '请联系管理员'
  });
});

// 404处理
app.use((req, res) => {
  res.status(404).json({
    success: false,
    message: '接口不存在',
    path: req.url
  });
});

// 启动服务器
async function startServer() {
  try {
    // 测试数据库连接
    const connected = await testConnection();
    if (!connected) {
      console.error('🚫 无法启动服务器: 数据库连接失败');
      process.exit(1);
    }
    
    app.listen(PORT, () => {
      console.log('🐾 流浪动物之家 API 服务器启动成功! (数据库版)');
      console.log(`📡 API地址: http://localhost:${PORT}`);
      console.log(`💚 健康检查: http://localhost:${PORT}/api/health`);
      console.log(`📊 系统统计: http://localhost:${PORT}/api/stats`);
      console.log('📋 可用接口:');
      console.log('   GET  /api/adoption-cases     # 领养案例');
      console.log('   GET  /api/pet-knowledge      # 宠物知识');
      console.log('   GET  /api/pet-news          # 宠物新闻');
      console.log('   GET  /api/articles/:id      # 文章详情');
      console.log('   GET  /api/rescue-cases/:type # 救助案例');
      console.log('   GET  /api/guestbook         # 留言列表');
      console.log('   POST /api/guestbook         # 提交留言');
      console.log('   GET  /api/contact-info      # 联系信息');
      console.log('   GET  /api/site-config       # 网站配置');
      console.log('   GET  /api/stats             # 系统统计');
      console.log('================================');
      console.log('🗄️  数据库: MySQL');
      console.log(`📍 数据库: ${process.env.DB_USER}@${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_NAME}`);
    });
  } catch (error) {
    console.error('启动服务器失败:', error);
    process.exit(1);
  }
}

// 优雅关闭
process.on('SIGINT', () => {
  console.log('\n🛑 正在关闭服务器...');
  process.exit(0);
});

process.on('SIGTERM', () => {
  console.log('\n🛑 正在关闭服务器...');
  process.exit(0);
});

startServer().catch(console.error);

module.exports = app;
